package com.qianfeng.zhangwei.day26.task;

import android.os.AsyncTask;
import android.text.TextUtils;
import android.widget.BaseAdapter;

import com.alibaba.fastjson.JSONObject;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.qianfeng.zhangwei.day26.bean.AppBean;
import com.qianfeng.zhangwei.day26.bean.ShopInfo;
import com.qianfeng.zhangwei.day26.utils.HttpUtils;

import java.util.List;

/**
 * @说 明：
 * @项目名称：Sz1504
 * @包 名： com.qianfeng.zhangwei.day26.task
 * @类 名： MainTask
 * @创 建人： zhangwei
 * @创建时间：2015-07-20 15:56
 * @版 本：v1.0
 * @修 改人：
 * @修改时间：
 * @修改备注：
 */
public class MainTask extends AsyncTask<String, Void, List<ShopInfo>> {

    private BaseAdapter baseAdapter;

    private List<ShopInfo> shopInfoList;
    private PullToRefreshListView ptrListView;

    private int page;


    public MainTask(BaseAdapter baseAdapter, List<ShopInfo> shopInfoList, PullToRefreshListView ptrListView, int page) {
        this.baseAdapter = baseAdapter;
        this.shopInfoList = shopInfoList;
        this.ptrListView = ptrListView;
        this.page = page;
    }

    /**
     * HttpClient   阿帕奇   ------ 已经废弃
     * httpUrlconnection  java  -----
     *
     * @param params
     * @return
     */
    @Override
    protected List<ShopInfo> doInBackground(String... params) {
        List<ShopInfo> shopInfoList = null;
        String result = HttpUtils.getDataFromServer(params[0]);
        /**
         *  官网json解析 必须掌握
         *  fastjson   可选
         *  Gson       可选
         */
        if (!TextUtils.isEmpty(result)) {
            AppBean app = JSONObject.parseObject(result, AppBean.class);
            if (app != null && app.getResult() != null) {
                shopInfoList = app.getResult().getData();
            }
        }
        return shopInfoList;
    }

    @Override
    protected void onPostExecute(List<ShopInfo> shopInfos) {
        super.onPostExecute(shopInfos);
        ptrListView.onRefreshComplete();
        if (shopInfos != null && shopInfos.size() > 0) {
            if (page == 1 && shopInfoList.size() > 0) {
                shopInfoList.clear();
            }
            shopInfoList.addAll(shopInfos);
            baseAdapter.notifyDataSetChanged();
        }
        //通知刷新完成
    }
}
